package cn.com.dhee.springcloudtraining.order.controller;

import cn.com.dhee.springcloudtraining.order.api.OrderServiceFeign;
import cn.com.dhee.springcloudtraining.order.api.qo.OrderQO;
import cn.com.dhee.springcloudtraining.order.api.vo.OrderVO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ralphwong
 */
@RestController
@RequestMapping("/order")
public class OrderController implements OrderServiceFeign {
    private Logger logger = LoggerFactory.getLogger(OrderController.class);
    /**
     * /order/info?orderId=abc
     * @param orderId
     * @return
     */
    @Override
    @PostMapping(value = "/info")
    public OrderVO info(@RequestParam(name = "orderId") String orderId){
        OrderVO vo = new OrderVO();
        vo.setOrderNo("info接口返回");
        return vo;
    }

    private static int hystirxCount = 0;

    /**
     * 查询订单-hystrix
     * @param qo
     * @return
     * @throws InterruptedException
     */
    @Override
    @PostMapping(value = "/select")
    @HystrixCommand(fallbackMethod = "selectByHystrix",commandProperties = {@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1"),})
    public List<OrderVO> select(@RequestBody OrderQO qo) throws InterruptedException {
        // 假装偶尔发生了bug
        hystirxCount = hystirxCount+1;
        logger.info("调用次数 {}",hystirxCount);
        // 偶尔发生时
        if (hystirxCount%2 == 0){
            Thread.sleep(5000);
        }
        // 一直发生时：
//        Thread.sleep(90000);

        List<OrderVO> list = new ArrayList<>();
        OrderVO vo = new OrderVO();
        vo.setOrderNo("正常订单");
        list.add(vo);
        return list;
    }
    @PostMapping(value = "/selectByHystrix")
    public List<OrderVO> selectByHystrix(@RequestBody OrderQO qo){
        List<OrderVO> list = new ArrayList<>();
        OrderVO vo = new OrderVO();
        vo.setOrderNo(null);
        vo.setRemark("服务不存在，返回个没有订单号的对象");
        list.add(vo);
        return list;
    }
}
